package com.educatioin.manage.web.schoolgradeclass.service;

import com.educatioin.commons.exceptions.ServiceException;
import com.educatioin.manage.web.productorder.response.ListOrderRsp;
import com.educatioin.manage.web.schoolgradeclass.po.SchoolGradeClassPo;
import com.educatioin.manage.web.schoolgradeclass.repository.SchoolGradeClassRepository;
import com.educatioin.manage.web.schoolgradeclass.request.CreateSchoolGradeClassReq;
import com.educatioin.manage.web.schoolgradeclass.request.ListSchoolGradeClassReq;
import com.educatioin.manage.web.schoolgradeclass.request.ModifySchoolGradeClassReq;
import com.educatioin.manage.web.schoolgradeclass.response.ListSchoolGradeClassRsp;
import com.educatioin.manage.web.system.po.CustomerPo;
import com.educatioin.manage.web.system.service.CustomerService;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by caizh on 18-5-5.
 */
@Service
public class SchoolGradeClassService {

    @Resource
    private SchoolGradeClassRepository schoolGradeClassRepository;

    @Resource
    private CustomerService customerService;

    public SchoolGradeClassRepository getSchoolGradeClassRepository() {
        return schoolGradeClassRepository;
    }

    public ListSchoolGradeClassRsp list(ListSchoolGradeClassReq req) {
        if(null == req.getPage() || req.getPage() <= 0
                || null == req.getLimit() || req.getLimit() <= 0){
            throw new ServiceException("分页查询错误！");
        }

        int page = req.getPage();
        if(page > 0) {
            page = page -1;
        }

        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageRequest = new PageRequest(page, req.getLimit(), sort);

        Page<SchoolGradeClassPo> retPage = schoolGradeClassRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = Lists.newArrayList();
            if(StringUtils.isNoneBlank(req.getSchoolName())) {
                predicates.add(cb.and(cb.equal(root.get("schoolName"), req.getSchoolName())));
            }
            if(StringUtils.isNoneBlank(req.getGrade())) {
                predicates.add(cb.and(cb.equal(root.get("grade"), req.getGrade())));
            }
            if(StringUtils.isNoneBlank(req.getClazz())) {
                predicates.add(cb.and(cb.equal(root.get("clazz"), req.getClazz())));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest);

        ListSchoolGradeClassRsp rsp = new ListSchoolGradeClassRsp();
        rsp.setCount((int) retPage.getTotalElements());
        if (CollectionUtils.isNotEmpty(retPage.getContent())) {
            Iterable<CustomerPo> custs = customerService.getCustomerRepository().findAll(retPage.getContent().stream()
                    .map(c -> {
                        if (StringUtils.isBlank(c.getRecommenderIds())) {
                            return -1L;
                        }
                        return Long.valueOf(c.getRecommenderIds());

                    }).collect(Collectors.toList()));
            Map<Long, String> custMap = Maps.newHashMap();
            custs.forEach(c -> custMap.put(c.getId(), c.getName()));
            retPage.getContent().forEach(c -> {
                if (StringUtils.isNoneBlank(c.getRecommenderIds())) {
                    c.setRecommenders(
                            Optional.ofNullable(custMap.get(Long.valueOf(c.getRecommenderIds()))).orElse(""));
                }
            });
        }
        rsp.setData(retPage.getContent());
        rsp.setReturnCode(ListOrderRsp.RETURN_SUCCESS_CODE);

        return rsp;
    }

    public void modify(ModifySchoolGradeClassReq req) {
        SchoolGradeClassPo school = schoolGradeClassRepository.findOne(req.getId());
        Optional.ofNullable(req.getSchoolName()).ifPresent(school::setSchoolName);
        Optional.ofNullable(req.getClazz()).ifPresent(school::setClazz);
        Optional.ofNullable(req.getGrade()).ifPresent(school::setGrade);
        Optional.ofNullable(req.getRecommenderIds()).ifPresent(school::setRecommenderIds);

        schoolGradeClassRepository.save(school);
    }

    public void create(CreateSchoolGradeClassReq req) {
        SchoolGradeClassPo po = new SchoolGradeClassPo();
        po.setClazz(req.getClazz());
        po.setSchoolName(req.getSchoolName());
        po.setGrade(req.getGrade());
        po.setRecommenderIds(req.getRecommenderIds());

        schoolGradeClassRepository.save(po);

    }

    public SchoolGradeClassPo findById(Long id) {
        return schoolGradeClassRepository.findOne(id);
    }
}
